package top.meijhm.communitymanagement.common.auth.filter;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import top.meijhm.communitymanagement.common.auth.jwt.JwtUtils;
import top.meijhm.communitymanagement.common.auth.model.UserDetailServiceImpl;
import top.meijhm.communitymanagement.user.service.UserService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserDetailServiceImpl userDetailService;
    @Autowired
    UserService userService;


    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        final String requestHeader = request.getHeader(jwtUtils.HEADER_STRING);  // 从header 中获取token
        if (StrUtil.isBlankOrUndefined(requestHeader)) {
            chain.doFilter(request, response);
            return;
        }

        if (requestHeader != null && requestHeader.startsWith(jwtUtils.TOKEN_PREFIX)) {  // token 以 Bearer 为前缀，表示 Bearer Token ，区别于MAC Token
            String token = requestHeader.replace(JwtUtils.TOKEN_PREFIX, "");
            String username = jwtUtils.getUsernameFromToken(token); // 从token中解析出 username

            // 验证token
            if (username != null && jwtUtils.validateToken(token, username)) {
                UserDetails userDetails = userDetailService.loadUserByUsername(username);  // 查询UserDetails
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);  // 在上下文中记录UserDetails
            }
            chain.doFilter(request, response);
        }
    }
}